package com.roger.uia.helper.util;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.Telephony;
import android.support.test.InstrumentationRegistry;
import com.roger.uia.helper.UiBase;


@SuppressLint("Recycle")
public class ContentUtils {
    private static final String TAG = "Test" + ContentUtils.class.getSimpleName();
    private Uri[] uri={ContactsContract.Contacts.CONTENT_URI,ContactsContract.CommonDataKinds.Phone.CONTENT_URI};
    private String[] columns={ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
    private ContentResolver cr =InstrumentationRegistry.getTargetContext().getContentResolver();

    public static ContentUtils content(){ return new ContentUtils(); }

    /**
     *
     * @return  true if exist contacts
     */
    public Boolean existContact(){
        return !getAllContactName().equals("");
    }

    /**
     *
     * @param name   the target content
     * @return       true if exist target contacts
     */
    public Boolean existContact(String name){
        return getAllContactName().contains(name);
    }

    /**
     *
     * @return   all contacts name
     */
    public String getAllContactName(){
        StringBuilder sb = new StringBuilder();
        Cursor c =cr.query(uri[0],null,null,null,null);
        while ( c!=null && c.moveToNext()){
            String name=c.getString(c.getColumnIndex(columns[1]));
            sb.append(name).append("\n");
        }
        return sb.toString();
    }

    /**
     *
     * @return  all contacts phone number
     */
    public String getAllContactPhoneNum(){
        StringBuilder sb = new StringBuilder();
        Cursor c =cr.query(uri[0],null,null,null,null);
        while ( c!=null && c.moveToNext()){
            int id = c.getInt(c.getColumnIndex(columns[0]));
            String name=c.getString(c.getColumnIndex(columns[1]));
            Cursor p = cr.query(uri[1],null,columns[3]+"="+id,null,null);
            while ( p!=null && p.moveToNext()){
                String phone = p.getString(p.getColumnIndex(columns[2]));
                sb.append(id).append(" ").append(name).append(" ").append(phone).append("\n");
            }
        }
        return sb.toString();
    }

    /**
     *add content info
     * @param name         content name
     * @param phoneNum     content phone number
     */
    public void addContact(String name, String phoneNum,String email,String address) {
        ContentValues cv = new ContentValues();
        Uri uri = cr.insert(ContactsContract.RawContacts.CONTENT_URI, cv);
        long contact_id = ContentUris.parseId(uri);

        uri = ContactsContract.Data.CONTENT_URI;
        String raw_contact_id = ContactsContract.Data.RAW_CONTACT_ID;
        String data2 = ContactsContract.Data.DATA2;
        String data1 = ContactsContract.Data.DATA1;

        cv.put(raw_contact_id, contact_id);
        cv.put(ContactsContract.CommonDataKinds.Phone.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
        cv.put(data2, name);
        cv.put(data1, name);
        cr.insert(uri,cv);
        cv.clear();

        cv.put(raw_contact_id, contact_id);
        cv.put(ContactsContract.CommonDataKinds.Phone.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
        cv.put(data2, phoneNum);
        cv.put(data1, phoneNum);
        cr.insert(uri, cv);
        cv.clear();


        cv.put(raw_contact_id, contact_id);
        cv.put(ContactsContract.CommonDataKinds.Phone.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
        cv.put(data2, email);
        cv.put(data1, email);
        cr.insert(uri, cv);
        cv.clear();

        cv.put(raw_contact_id, contact_id);
        cv.put(ContactsContract.CommonDataKinds.Phone.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
        cv.put(data2, address);
        cv.put(data1, address);
        cr.insert(uri, cv);
        cv.clear();

    }

    /**
     *
     * @param name         content name
     * @param phoneNum    the phone number will be updated
     */
    public void updateContactPhoneNum(String name, String phoneNum) {
        ContentValues values = new ContentValues();
        values.put(ContactsContract.Data.DATA1, phoneNum);
        cr.update(ContactsContract.Data.CONTENT_URI, values, ContactsContract.Data.MIMETYPE + "=? and " + ContactsContract.PhoneLookup.DISPLAY_NAME + "=?",
                new String[]{ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, name});
    }

    /**
     *
     * @param name     the content wil be deleted
     */
    public void delContact(String name) {
        Cursor c = cr.query(ContactsContract.RawContacts.CONTENT_URI, new String[]{ContactsContract.Data._ID}, ContactsContract.PhoneLookup.DISPLAY_NAME + "=?", new String[]{name}, null);
        if (c!=null && c.moveToFirst()) {
            int id = c.getInt(0);
            cr.delete(ContactsContract.RawContacts.CONTENT_URI, ContactsContract.PhoneLookup.DISPLAY_NAME + "=?", new String[]{name});
            cr.delete(ContactsContract.Data.CONTENT_URI, ContactsContract.Data.RAW_CONTACT_ID + "=?", new String[]{id + ""});
        }
    }

    public void delAllContact() {
        Cursor c = cr.query(ContactsContract.RawContacts.CONTENT_URI, null, null, null, null);
        if (c!=null && c.moveToNext()) {
            cr.delete(ContactsContract.RawContacts.CONTENT_URI, null, null);
            cr.delete(ContactsContract.Data.CONTENT_URI, null, null);
        }
    }

    /**
     *
     * @return   all sms
     */

    public String getAllSms() {
        StringBuilder sb = new StringBuilder();
        Cursor c = cr.query(Telephony.Sms.CONTENT_URI, null, null, null, Telephony.Sms.Conversations.DEFAULT_SORT_ORDER);
        try {
           while (c!=null && c.moveToNext()) {
               int index_Date = c.getColumnIndex(Telephony.Sms.DATE);
               int index_Person = c.getColumnIndex(Telephony.Sms.PERSON);
               int index_Address = c.getColumnIndex(Telephony.Sms.ADDRESS);
               int index_Body = c.getColumnIndex(Telephony.Sms.BODY);
               long date = c.getLong(index_Date);
               String person = c.getString(index_Person);
               String address = c.getString(index_Address);
               String body = c.getString(index_Body);
               sb.append("[").append(UiBase.dateFormat.format(date)).append(" ").append(person).append(" ").append(address).append(" ").append(body).append("]\n");
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public String getContentTargetInfo(String uri,String target) {
        StringBuilder sb = new StringBuilder();
        Cursor c = cr.query(Uri.parse(uri), null, null, null, null);
        try {
            while (c!=null && c.moveToNext()) {
                int index_data = c.getColumnIndex(target);
                String date = c.getString(index_data);
                sb.append("[").append(date).append("]\n");
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public void updateContentTargetInfo(String uri, String target,String change,String where,String[] selectionArgs) {
        ContentValues values = new ContentValues();
        values.put(target,change);
        cr.update(Uri.parse(uri), values, where, selectionArgs);
    }


}
